/** 基本socketAPI的使用
 *  @date 2021.02.18
 *  @author Lu
 */
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>

static bool stop = false;

static void handle_term(int sig)
{
	stop = true;
}

int main(int argc,char* argv[])
{
	signal(SIGTERM,handle_term);

	if(argc <= 3)
	{
		printf("参数太少!");
		return 1;
	}

	const char* ip = argv[1];
	int port = atoi(argv[2]);
	int backlog = atoi(argv[3]);

	int sock = socket(AF_INET,SOCK_STREAM,0);
	assert(sock >=0);
	printf("Create successful!\n");

	struct sockaddr_in address;
	bzero(&address,sizeof(address));
	address.sin_family = AF_INET;
	inet_pton(AF_INET,ip,&address.sin_addr);
	address.sin_port = htons(port);

	int ret = bind(sock,(struct sockaddr*)&address,sizeof(address));
	assert(ret >= 0);
	printf("Bind succeddful!\n");
	
	ret = listen(sock,backlog);
	assert(ret != -1);
	printf("listening...\n");

	while(!stop)
	{
		struct sockaddr_in client;
		socklen_t clientaddr_length = sizeof(client);
		int connfd = accept(sock,(struct sockaddr*)&client,&clientaddr_length);

		if(connfd <0)
		{
			printf("Connecting faild! The errno is:%d\n",errno);
		}
		else
		{
			char* client_ip = inet_ntoa(client.sin_addr);
			int client_port = ntohs(client.sin_port);
			printf("Connected with ip:%s and port:%d\n",client_ip,client_port);
			close(connfd);
		}
	}
	close(sock);
	return 0;
}

